package cn.controller;

import cn.entity.Result;
import cn.entity.SysResource;
import cn.entity.SysUser;
import cn.service.SysResourceService;
import cn.service.SysUserService;
import cn.utils.EncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/common")
public class CommomController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysResourceService sysResourceService;

    @RequestMapping("/navbar")
    public String navbar(){
        return "/common/navbar";
    }

    @RequestMapping("/mainContainer")
    public String mainContainer(){
        return "/common/mainContainer";
    }

    @RequestMapping("/index")
    public String index(){
        return "index";
    }
    @RequestMapping("/login")
    public String login(){
        return "login";
    }
    @RequestMapping("/notlogin")
    public String notlogin(){
        return "notlogin";
    }

    @RequestMapping("/check")
    @ResponseBody
    public Result check(String username, String password, String code, HttpSession session){
        String vcode = (String) session.getAttribute("vcode");
        SysUser sysUser=null;
        if (vcode!=null&&vcode.equals(code)){
            SysUser user = new SysUser();
            user.setUsername(username);
            user.setPassword(EncryptUtils.MD5_HEX(EncryptUtils.MD5_HEX(password)+username));
            user.setDelFlag("0");
//            System.out.println(EncryptUtils.MD5_HEX(EncryptUtils.MD5_HEX(password) + username));
            sysUser = sysUserService.selectOne(user);
            if (sysUser!=null){
                sysUser.setPassword(null);
                sysUser.setUrl(sysResourceService.selectResourceByUid(sysUser.getId()));
                session.setAttribute("user",sysUser);
                return new Result(true,"登录成功",sysUser);
            }else {
                return new Result(false,"账号或密码错误",null);
            }
        }
        return new Result(false,"验证码错误",null);
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }

}
